package org.jiuling.spring.unifyinfo.response.handing;

import com.alibaba.fastjson2.JSON;
import org.jiuling.network.tools.response.enums.ResponseCodeEnum;
import org.jiuling.spring.unifyinfo.response.annotation.ResponseData;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应数据通知
 * @author 紫灵
 * @date 2023年03月31日 10时53分17秒
 */
@RestControllerAdvice
public class ResponseDataAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !returnType.getParameterType().isAssignableFrom(org.jiuling.network.tools.response.ResponseData.class) && returnType.hasMethodAnnotation(ResponseData.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseData responseData = returnType.getMethodAnnotation(ResponseData.class);
        org.jiuling.network.tools.response.ResponseData<Object> objectResponseData = new org.jiuling.network.tools.response.ResponseData<>(ResponseCodeEnum.SUCCESS, responseData.successMsg(), body);
        if(body instanceof String){
            return JSON.toJSONString(objectResponseData);
        }
        return objectResponseData;
    }
}
